package com.wwj.auction.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwj.auction.common.util.SystemUtil;
import com.wwj.auction.login.entity.Shop;
import com.wwj.auction.login.entity.Store;
import com.wwj.auction.login.entity.vo.*;
import com.wwj.auction.login.enums.ShopCommitModelEnum;
import com.wwj.auction.login.enums.ShopModelEnum;
import com.wwj.auction.login.enums.ShopStatusEnum;
import com.wwj.auction.login.mapper.ShopMapper;
import com.wwj.auction.login.mapper.StoreMapper;
import com.wwj.auction.login.service.ShopService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wwj
 * @since 2021-08-27
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements ShopService {

    @Resource
    private StoreMapper storeMapper;

    @Override
    public List<ShopVo> listToShopVo() {
        List<Shop> shopList = this.list();
        // 封装成Vo数据
        List<ShopVo> shopVoList = shopList.stream().map(shop -> {
            ShopVo shopVo = new ShopVo();
            shopVo.setShopId(shop.getId());
            shopVo.setShopName(shop.getShopName());
            shopVo.setShopStartPrice(shop.getShopStartPrice());
            shopVo.setShopIndexImage(shop.getShopIndexImage());
            return shopVo;
        }).collect(Collectors.toList());
        return shopVoList;
    }

    @Override
    public void putShop(ShopDetailVo shopDetailVo) {
        // 封装数据
        Shop shop = new Shop();
        // 属性拷贝
        BeanUtils.copyProperties(shopDetailVo, shop);
        // 处理拍卖模式
        String shopModel = shopDetailVo.getShopModel();
        if (shopModel.equals(ShopModelEnum.SHOP_AUCTION.getMsg())) {
            shop.setShopModel(ShopModelEnum.SHOP_AUCTION.getStatus());
        } else if (shopModel.equals(ShopModelEnum.SHOP_BIDDING.getMsg())) {
            shop.setShopModel(ShopModelEnum.SHOP_BIDDING.getStatus());
        }
        // 处理成交模式
        String commitModel = shopDetailVo.getCommitModel();
        if (commitModel.equals(ShopCommitModelEnum.COMMIT_ORDINARY.getMsg())) {
            shop.setCommitModel(ShopCommitModelEnum.COMMIT_ORDINARY.getStatus());
        } else if (commitModel.equals(ShopCommitModelEnum.COMMIT_IMMEDIATE.getMsg())) {
            shop.setCommitModel(ShopCommitModelEnum.COMMIT_IMMEDIATE.getStatus());
        }
        // 设置商品状态为拍卖中
        shop.setStatus(ShopStatusEnum.SELLING.getStatus());
        // 设置商品当前价格为初始价格
        shop.setShopCurrentPrice(shopDetailVo.getShopStartPrice());
        // 通过卖家的用户id查询店铺id
        Integer sellerId = shopDetailVo.getSellerId();
        Store store = storeMapper.selectOne(
                Wrappers.lambdaQuery(Store.class)
                        .eq(Store::getUserId, sellerId));
        shop.setStoreId(store.getId());
        // 保存
        baseMapper.insert(shop);
    }

    @Override
    public PageModel<AuctionListShopVo> listForShop(Integer id, Integer page, Integer limit) {
        // 通过用户id查询属于它的商品
        LambdaQueryWrapper<Shop> wrapper = Wrappers.
                lambdaQuery(Shop.class).
                eq(Shop::getSellerId, id);
        // 按id降序排序
        wrapper.orderByDesc(Shop::getId);
        Page<Shop> shopPage = new Page<>(page, limit);
        List<Shop> shopList = baseMapper.selectPage(shopPage, wrapper).getRecords();
        // 封装Vo数据
        List<AuctionListShopVo> shopVoList = shopList.stream().map(shop -> {
            AuctionListShopVo shopVo = new AuctionListShopVo();
            shopVo.setShopIndexImage(shop.getShopIndexImage());
            shopVo.setShopName(shop.getShopName());
            shopVo.setEarnestMoney(shop.getEarnestMoney().toString());
            shopVo.setShopCurrentPrice(shop.getShopCurrentPrice().toString());
            // 设置开拍时间
            LocalDateTime startTime = shop.getStartTime();
            shopVo.setStartTime(SystemUtil.parseDate(startTime));
            // 设置结束时间
            LocalDateTime endTime = shop.getEndTime();
            shopVo.setEndTime(SystemUtil.parseDate(endTime));
            shopVo.setStatus(String.valueOf(shop.getStatus()));
            // 设置商品的id
            shopVo.setId(shop.getId());
            return shopVo;
        }).collect(Collectors.toList());
        // 封装最终数据
        PageModel<AuctionListShopVo> pageModel = new PageModel<>();
        pageModel.setList(shopVoList);
        pageModel.setTotal(shopPage.getTotal());
        return pageModel;
    }

    @Override
    public void status(Integer shopId, Integer shopStatus) {
        // 根据id查询商品详情
        Shop shop = baseMapper.selectById(shopId);
        // 修改商品状态
        shop.setStatus(shopStatus);
        // 更新
        baseMapper.updateById(shop);
    }

    @Override
    public ShopDetailTempVo detail(Integer shopId) {
        // 根据id查询商品信息
        Shop shop = baseMapper.selectById(shopId);
        // 封装Vo数据
        ShopDetailTempVo shopDetailTempVo = new ShopDetailTempVo();
        shopDetailTempVo.setShopName(shop.getShopName());
        shopDetailTempVo.setShopCurrentPrice(shop.getShopCurrentPrice());
        shopDetailTempVo.setEarnestMoney(shop.getEarnestMoney());
        shopDetailTempVo.setShopSmallImage(shop.getShopSmallImage());
        shopDetailTempVo.setShopBigImage(shop.getShopBigImage());
        shopDetailTempVo.setStatus(shop.getStatus());
        // 计算当前商品距离拍卖结束的时间
        LocalDateTime endTime = shop.getEndTime();
        LocalDateTime nowTime = LocalDateTime.now();
        LocalDateTime tempTime = LocalDateTime.from(nowTime);

        long day = nowTime.until(endTime, ChronoUnit.DAYS);
        // 将tempTime后移day天
        tempTime = tempTime.plusDays(day);
        long hour = tempTime.until(endTime, ChronoUnit.HOURS);
        // 将tempTime后移hour小时
        tempTime = tempTime.plusHours(hour);
        long minute = tempTime.until(endTime, ChronoUnit.MINUTES);
        // 将tempTime后移minute分钟
        tempTime = tempTime.plusMinutes(minute);
        long second = tempTime.until(endTime, ChronoUnit.SECONDS);

        // 获取天、时、分、秒
        shopDetailTempVo.setDay(day);
        shopDetailTempVo.setHour(hour);
        shopDetailTempVo.setMinute(minute);
        shopDetailTempVo.setSecond(second);
        shopDetailTempVo.setUserInfo(null);
        // TODO 若当前时间已经在拍卖时间之后，说明拍卖结束
        Duration duration = Duration.between(nowTime, endTime);
        if (duration.toMillis() <= 0) {
            // 如果商品已撤拍或已成交，则无需修改
            if (shop.getStatus() == 1) {
                shopDetailTempVo.setStatus(-1);
            }
        }
        shopDetailTempVo.setShopAddPrice(shop.getShopAddPrice());
        return shopDetailTempVo;
    }

    @Override
    public List<Shop> scanShop() {
        List<Shop> shopList = baseMapper.selectList(Wrappers.emptyWrapper());
        // 过滤得到已经结束拍卖的拍品
        List<Shop> filterShopList = shopList.stream().filter(shop -> {
            LocalDateTime endTime = shop.getEndTime();
            // 比较结束拍卖时间与当前时间
            LocalDateTime nowTime = LocalDateTime.now();
            // 若现在的时间已经在结束拍卖时间之后，这说明拍卖结束
            boolean filterFlag = nowTime.isAfter(endTime);
            return filterFlag;
        }).collect(Collectors.toList());
        return filterShopList;
    }
}
